const router = require("express").Router();
const { User } = require('@/models')
const { sign } = require('@/utils/token')
const { login, register } = require('@/joi/user')
const expressJoi = require('@escook/express-joi')
const { data } = require('@/utils/send');
router.post('/login', expressJoi(login), async (req, res) => {
    try {
        const { username, password, sta } = req.body
        const user = await User.findOne({ where: { username } })
        if (!user) return res.cc('用户不存在')
        if (user.password !== password) return res.cc('密码错误')
        if (user.sta !== sta) return res.cc('用户权限错误')
        if (user.sta === 1) {
            const datas = data({ message: '登录成功', data: user, })
            res.send(datas)
            res.locals.data = datas;
        } else {
            const datas = { code: 200, message: '登录成功', data: user, token: sign({ username: user.username }) }
            res.send(datas)
            res.locals.data = datas;
        }
    } catch (error) {
        console.log(error)
        res.cc(error)
    }
})
router.post('/register', expressJoi(register), async (req, res) => {
    try {
        const { username, password, phone } = req.body
        const user = await User.findOne({ where: { username } })
        console.log(user)
        if (user) return res.cc('用户名已存在')
        const newUSer = await User.create({ username, password, phone })
        if (!newUSer) return res.cc('注册失败')
        const datas = data({ message: '注册成功', data: newUSer })
        res.send(datas)
        res.locals.data = datas;
    } catch (error) {
        console.log(error)
        res.cc(error)
    }
})

module.exports = router